/*
 * @author : TF-BJ-C064
 * @creation : 2014-6-26 下午4:32:56
 * @description : 
 *
 */

package com.action.park;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.base.BaseAction;
import com.base.UserBean;
import com.bean.ParkAccountRecord;
import com.bean.ParkManager;
import com.bean.ParkOrder;
import com.bean.PayMent;
import com.bean.TransactionRecord;
import com.service.ParkManagerService;
import com.service.ParkOrderService;
import com.service.PayStatisticsService;
import com.service.TransactionRecordService;
import com.tool.DateTimeTools;
import com.tool.RegexTool;
import com.util.GUtil;
/**
 * 我的停车场收支统计
 * <p>Title: MyPayStatistics</p>
 * <p>Description: </p>
 * <p>Company: www.teleframe.cn</p> 
 * @author	lijian
 * @date	2014-6-26
 */
public class MyPayStatisticsAction extends BaseAction {

	private Logger log = Logger.getLogger(MyPayStatisticsAction.class);
	private static String Tag = MyPayStatisticsAction.class.getName();

	PayStatisticsService payStatisticsService;//交易记录Service
	ParkManagerService parkManagerService;

	String stattype; // day, week, month, year
	String datetime; // "yyyy-MM-dd", "yyyy-MM-dd", "yyyy-MM", "yyyy"
	JSONObject json;
	
	// 手机测试地址
	// http://192.168.0.100:9010/ipark/ParkLogin?method=login&userId=10&token=MGJlNjg2NmIzOTAzMmFmOTU3YmFlOTA5Y2JmOTA4Nzc=&RedirectUrl=MyPayStatisticsAction
	
	private ParkManager parkManager;

	@Override
	public String handle() throws Exception {
		this.setHeaderTitle("收支统计");
		return GUtil.SUCCESS;
	}
	

	/**
	 * 查询
	 * <p>Title: query</p>
	 * <p>Description: 
	 * 		PC端网页查询会直接进入此处，手机端调用会通过handle()中转
	 * </p>
	 * @return
	 * @throws Exception
	 * @see com.base.BaseAction#query()
	 */
	@Override
	public String query() throws Exception {
		this.setHeaderTitle("收支统计");
		log.info("MyPayStatistics");
		boolean bPass = true;
		if(stattype==null){
			bPass = false;
			this.setMsg("类型错误"); 
		}
		if(datetime==null){
			bPass = false;
			this.setMsg("时间类型错误"); 
		}
		if(bPass){
			if(stattype.equals("day")){
				return this.queryByDay();
			}else if(stattype.equals("week")){
				return this.queryByWeek();
			}else if(stattype.equals("month")){
				return this.queryByMonth();
			}else if(stattype.equals("year")){
				return this.queryByYear();
			}
			this.setMsg("参数错误  ");
		}

		PrintWriter out = response.getWriter();
		out.print( this.getMsg());
		out.close();

		return GUtil.NONE;
	}


	/**
	 * 按天查询收支
	 * <p>Title: queryByDay</p>
	 * <p>Description: </p>
	 * @return json
	 * @throws Exception 
	 */
	public String queryByDay() throws Exception{
		String daytime = datetime.substring(0,10).trim();

		log.info(Tag+".queryByDay() daytime="+daytime);

		List<ParkAccountRecord> payInOut = new ArrayList<ParkAccountRecord>();//收支统计
		List<ParkAccountRecord> payStat = new ArrayList<ParkAccountRecord>();//收支统计(根据类型统计)

		json = new JSONObject();

		if(RegexTool.checkDateTime(daytime)){
			String ret = payStatisticsService.queryByDay(payInOut, payStat, daytime, user.getId());//
			if(ret.endsWith(GUtil.SUCCESS)){
				json.put("error", 0);
				json.put("msg", "操作成功");
				json.put("payInOut", JSONArray.fromObject( payInOut ) );
				json.put("payStat", JSONArray.fromObject( payStat ) );
			}else{
				json.put("error", -1);
				json.put("msg", "操作失败 "+ret);
			}
		}else{
			json.put("error", -1);
			json.put("msg", "操作失败 日期格式错误");
		}
		
		log.info(Tag+" "+json.toString());
		
		PrintWriter out = response.getWriter();
		out.print(json.toString());
		out.close();

		return GUtil.NONE;
	}
	public String queryByWeek() throws Exception{
		
		PrintWriter out = response.getWriter();
		if( !RegexTool.checkDateTime(datetime) ){
			log.info("输入日期错误 datetime="+datetime);
			out.print("输入日期错误"+datetime);
			out.close();
			return GUtil.NONE;
		}
		SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
		//String datetime = "2014-01-08";
		Date timelong = formatDate.parse(datetime);
		Timestamp inTime = new Timestamp(timelong.getTime());
		Timestamp outStartTime = new Timestamp(timelong.getTime());
		Timestamp outEndTime = new Timestamp(timelong.getTime());
		DateTimeTools.getWeekDays(inTime, outStartTime, outEndTime);

		List<ParkAccountRecord> payInOut = new ArrayList<ParkAccountRecord>();//收支统计
		List<ParkAccountRecord> payStat = new ArrayList<ParkAccountRecord>();//收支统计(根据类型统计)
		Map<Double, Double> paylistInOutByDay = new HashMap<Double, Double>();

		json = new JSONObject();
		Double[][] data = payStatisticsService.queryByWeek(payInOut, payStat, paylistInOutByDay, datetime, user.getId());
		if(data!=null){
			json.put("error", 0);
			json.put("msg", "操作成功");
			json.put("payInOut", JSONArray.fromObject( payInOut ) );
			json.put("payStat", JSONArray.fromObject( payStat ) );
			//check 
			if(data.length!=3){
				json.put("error", -2);
				log.error(Tag+" 系统错误 queryByMonth");
				json.put("msg", "系统错误 ");
			}else{
				json.put("sum", data[0].length);
			}
			json.put("data", data);
			
		}else{
			json.put("error", -1);
			json.put("msg", "操作失败 ");
		}
		out.print(json);
		out.close();

		return GUtil.NONE;
	}
	public String queryByMonth() throws Exception{
		datetime =datetime.substring(0,7);
		PrintWriter out = response.getWriter();
		if( !RegexTool.checkMonth(datetime) ){
			log.info("输入日期错误 datetime="+datetime);
			out.print("输入日期错误"+datetime);
			out.close();
			return GUtil.NONE;
		}
		SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM");
		//String datetime = "2014-05";
		Date timelong = formatDate.parse(datetime);// for test it is the right time, otherwise throw ParseException
		
		List<ParkAccountRecord> payInOut = new ArrayList<ParkAccountRecord>();//收支统计
		List<ParkAccountRecord> payStat = new ArrayList<ParkAccountRecord>();//收支统计(根据类型统计)
		Map<Double, Double> paylistInOutByDay = new HashMap<Double, Double>();

		json = new JSONObject();
		Double[][] data = payStatisticsService.queryByMonth(payInOut, payStat, paylistInOutByDay, datetime, user.getId());
		if(data!=null){
			json.put("error", 0);
			json.put("msg", "操作成功");
			json.put("payInOut", JSONArray.fromObject( payInOut ) );
			json.put("payStat", JSONArray.fromObject( payStat ) );
			//check 
			if(data.length!=3){
				json.put("error", -2);
				log.error(Tag+" 系统错误 queryByMonth");
				json.put("msg", "系统错误 ");
			}else{
				json.put("sum", data[0].length);
			}
			json.put("data", data);
			
		}else{
			json.put("error", -1);
			json.put("msg", "操作失败 ");
		}
		out.print(json);
		out.close();
		
		return GUtil.NONE;
	}
	public String queryByYear() throws Exception{
		datetime =datetime.substring(0,4);
		PrintWriter out = response.getWriter();
		if( !RegexTool.checkYear(datetime) ){
			log.info("输入日期错误 datetime="+datetime);
			out.print("输入日期错误"+datetime);
			out.close();
			return GUtil.NONE;
		}
		SimpleDateFormat formatDate = new SimpleDateFormat("yyyy");
		//String datetime = "2014";
		Date timelong = formatDate.parse(datetime);// for test it is the right time, otherwise throw ParseException
		
		List<ParkAccountRecord> payInOut = new ArrayList<ParkAccountRecord>();//收支统计
		List<ParkAccountRecord> payStat = new ArrayList<ParkAccountRecord>();//收支统计(根据类型统计)
		Map<Double, Double> paylistInOutByDay = new HashMap<Double, Double>();

		json = new JSONObject();
		Double[][] data = payStatisticsService.queryByYear(payInOut, payStat, paylistInOutByDay, datetime, user.getId());
		if(data!=null){
			json.put("error", 0);
			json.put("msg", "操作成功");
			json.put("payInOut", JSONArray.fromObject( payInOut ) );
			json.put("payStat", JSONArray.fromObject( payStat ) );
			//check 
			if(data.length!=3){
				json.put("error", -2);
				log.error(Tag+" 系统错误 queryByMonth");
				json.put("msg", "系统错误 ");
			}else{
				json.put("sum", data[0].length);
			}
			json.put("data", data);
			
		}else{
			json.put("error", -1);
			json.put("msg", "操作失败 ");
		}
		out.print(json);
		out.close();
		
		return GUtil.NONE;
	}


	///blow not used

	@Override
	public String add() throws Exception {
		return GUtil.EDIT;
	}

	@Override
	public String update() throws Exception {
		return GUtil.EDIT;
	}

	@Override
	public String delete() throws Exception {
		return this.query();
	}

	@Override
	public String view() throws Exception {
		return GUtil.VIEW;
	}

	@Override
	public boolean validate(Object obj) throws Exception {
		return false;
	}

	public String getStattype() {
		return stattype;
	}

	public void setStattype(String stattype) {
		this.stattype = stattype;
	}

	public String getDatetime() {
		return datetime;
	}

	public void setDatetime(String datetime) {
		this.datetime = datetime;
	}

	public PayStatisticsService getPayStatisticsService() {
		return payStatisticsService;
	}
 
	public void setPayStatisticsService(PayStatisticsService payStatisticsService) {
		this.payStatisticsService = payStatisticsService;
	}

	public ParkManager getParkManager() {
		return parkManager;
	}

	public void setParkManager(ParkManager parkManager) {
		this.parkManager = parkManager;
	}


	public ParkManagerService getParkManagerService() {
		return parkManagerService;
	}

	public void setParkManagerService(ParkManagerService parkManagerService) {
		this.parkManagerService = parkManagerService;
	}

}
